package cn.sinata.wanglin.db.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;

import com.xilada.xldutils.utils.Utils;

import cn.sinata.wanglin.commonutils.Constant;
import cn.sinata.wanglin.db.DBHelper;
import cn.sinata.wanglin.db.DbUtils;
import cn.sinata.wanglin.net.model.PushData;

/**
 *
 * Created by liaoxiang on 16/12/31.
 */

public class PushDao {

    public static final String COLUMN_USER_ID = "userId";//接收者环信id。
    public static final String COLUMN_ACTION = "action";//类型
    public static final String COLUMN_EXT = "ext_content";//扩展字段
    public static final String COLUMN_IS_READ = "isRead";//是否已读
    public static final String COLUMN_TIME = "time";//是否已读

    private static DBHelper dbHelper;
    private PushDao(){}
    public static PushDao getInstance(Context context){
        dbHelper = DBHelper.getInstance(context);
        return PushDao.Singleton.INSTANCE;
    }

    private static final class Singleton {
        private final static PushDao INSTANCE= new PushDao();
    }

    public void savePushData(String userId,String action,String ext_content,String time){
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        if (db != null && db.isOpen()) {
            String tableName = getTableName(userId);
            if (!DbUtils.isTableExist(db,tableName)) {
                db.execSQL(getCreateTableSQLString(tableName));
            }
            ContentValues values = new ContentValues();
            values.put(COLUMN_USER_ID, userId);
            values.put(COLUMN_ACTION, action);
            values.put(COLUMN_EXT, ext_content);
            values.put(COLUMN_IS_READ, 0);
            if (!TextUtils.isEmpty(time)) {
                values.put(COLUMN_TIME, time);
            }
            Utils.systemErr("-save push data-->"+tableName+"--->"+ext_content);
            db.replace(tableName, null, values);
        }
    }

    /**
     * 读取圈子最新未读消息。
     * @param userId 用户环信帐号
     * @return
     */
    public PushData getLastUnReadCircleNewMessage(String userId) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        if (db != null && db.isOpen()) {
            String tableName = getTableName(userId);
            if (!DbUtils.isTableExist(db,tableName)) {
                return null;
            }
            Cursor cursor = db.rawQuery("select * from "+tableName+" where action = ? order by "+COLUMN_TIME+" desc limit 1",new String[]{ Constant.Push.CMD_MEG_TYPE_C});
            if (cursor.moveToFirst()) {
                String action = cursor.getString(cursor.getColumnIndex(COLUMN_ACTION));
                String ext = cursor.getString(cursor.getColumnIndex(COLUMN_EXT));
                PushData pushData = new PushData();
                pushData.setUserId(userId);
                pushData.setAction(action);
                pushData.setExt(ext);
                Utils.systemErr(pushData);
                cursor.close();
                return pushData;
            }

        }
        return null;
    }

    /**
     *
     * @param userId 环信id，不是平台id
     * @param action 类型
     */
    public int getUnReadNum(String userId,String action){
        Utils.systemErr("-getUnReadNum-");
        int count = 0;
        SQLiteDatabase db=dbHelper.getWritableDatabase();
        if (db!=null && db.isOpen()) {
            String table = getTableName(userId);
            if (!DbUtils.isTableExist(db,table)) {
                return count;
            }
            if (TextUtils.isEmpty(action)) {
                return count;
            }
            Cursor cursor = db.rawQuery("select count(*) from "+table+" where "+COLUMN_ACTION+" = ? and "+COLUMN_IS_READ +" = 0 ", new String[]{action});
            if (cursor.moveToNext()) {
                count = cursor.getInt(0);
            }
            cursor.close();
            return count;
        }
        return count;
    }

    /**
     * 设置圈子新消息为已读
     * @param userId 用户环信帐号
     */
    public void setCircleMessageAllRead(String userId){
        SQLiteDatabase db=dbHelper.getWritableDatabase();
        if (db!=null && db.isOpen()) {
            String table = getTableName(userId);
            if (!DbUtils.isTableExist(db,table)) {
                return;
            }
            ContentValues values = new ContentValues();
            values.put(COLUMN_IS_READ, 1);
            db.update(table, values,COLUMN_USER_ID + " = ? and "+COLUMN_ACTION + " = ?",new String[]{userId,Constant.Push.CMD_MEG_TYPE_C});
        }
    }

    public void setNewFriendMessageAllRead(String userId){
        SQLiteDatabase db=dbHelper.getWritableDatabase();
        if (db!=null && db.isOpen()) {
            String table = getTableName(userId);
            if (!DbUtils.isTableExist(db,table)) {
                return;
            }
            ContentValues values = new ContentValues();
            values.put(COLUMN_IS_READ, 1);
            db.update(table, values,COLUMN_USER_ID + " = ? and "+COLUMN_ACTION + " = ? ",new String[]{userId,Constant.Push.CMD_MEG_TYPE_F});
        }
    }

//    private boolean isTableExist(String tableName){
//        SQLiteDatabase db=dbHelper.getWritableDatabase();
//        if (db==null || !db.isOpen()) {
//            return false;
//        }
//        boolean result = false;
//        if (tableName == null) {
//            return false;
//        }
//        Cursor cursor = null;
//        try {
//            String sql = "select count(*) as c from Sqlite_master  where type ='table' and name ='"
//                    + tableName.trim() + "' ";
//            cursor = db.rawQuery(sql, null);
//            if (cursor.moveToNext()) {
//                int count = cursor.getInt(0);
//                if (count > 0) {
//                    result = true;
//                }
//            }
//
//        } catch (Exception e) {
//        }finally {
//            if (cursor != null) {
//                cursor.close();
//            }
//        }
//        return result;
//    }

    private String getTableName(String userId){
        return "push_"+userId;
    }

    private String getCreateTableSQLString(String tableName){
        String sql=null;
        if (TextUtils.isEmpty(tableName)) {
            return sql;
        }
        sql="CREATE TABLE "
                + tableName.trim() + "  ("
                + " id INTEGER PRIMARY KEY AUTOINCREMENT , "
                + COLUMN_USER_ID + " TEXT, "
                + COLUMN_ACTION + " TEXT, "
                + COLUMN_EXT + " TEXT, "
                + COLUMN_IS_READ + " TEXT, "
                + COLUMN_TIME + " TEXT); ";
        return sql;
    }
}
